import { departAndArrivePortsApi, getLinePortsByIdApi } from "../../api/index";
import { TRACER_PAGES, PRODUCT_CODE } from '../../utils/constants';
import { setEvent, setPage, queryString } from '../../utils/index'
const pageName = TRACER_PAGES['map']

Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentTab: "departPort",
    currentPort: {},
    markers: [],
    portsList: [],
    isShowNavigateBtn: true,
    canOrder: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this
    const { from, to, fromPort, toPort, lineId, isPort, canOrder } = options;
    const departCity = from && decodeURIComponent(from);
    const arriveCity = to && decodeURIComponent(to);
    const departPort = fromPort && decodeURIComponent(fromPort);
    const arrivePort = toPort && decodeURIComponent(toPort);
    const isQueryByPort = isPort === "1";
    const isShowNavigateBtn = true;
    const title = `${departCity} - ${arriveCity}`;
    wx.setNavigationBarTitle({
      title: title,
    });
    this.setData({
      canOrder,
      departCity,
      arriveCity,
      departPort,
      arrivePort,
      lineId,
      isQueryByPort,
      isShowNavigateBtn,
    });

    // 是否通过港口航线ID查询
    if (isQueryByPort) {
      that.getLinePort(parseInt(lineId))
        .then((res) => {
          
          if (res) {
            const departPortInfo = res.DeparturePortInfo;
            const arrivePortInfo = res.ArrivePortInfo;
            const list = [departPortInfo, arrivePortInfo];
            const portsList = that.formatPortsList(list);
            const currentPort = portsList.find(
              (item) => item.name === departPort
            );


            that.setData({
              portsList,
              currentPort
            });
          }
        })
        .catch((error) => {
          console.log("getLinePort函数", error);
        });
    } else {
      // 获取城市港口列表
      that.getCityLinePort(lineId)
        .then((res) => {
          if (res && res.length > 0) {
            const portsList = that.formatPortsList(res);
            const currentPort = portsList.find(
              (item) => item.name === departPort
            );
            that.setData({
              portsList,
              currentPort
            });
          }
        })
        .catch((error) => {
          console.log("getCityLinePort函数", error);
        });
    }
    
    setPage(pageName + '?' + queryString(options), PRODUCT_CODE)
  },

  
  /**
   * 格式化港口列表数据
   * @param {Array} portsList 港口列表
   * @returns {Array} 处理后的港口列表
   */
  formatPortsList (portsList) {
    // 由于后端经纬度错误，需要交换
    const ports = portsList.map(port => {
        return {
            id: port.PortId,
            name: port.PortName,
            address: port.PortAddress,
            phone: port.PortPhoneNo,
            ticketPoint: port.PortTicketPoint,
            latitude: port.PortLon,
            longitude: port.PortLat,
            surrounding: port.PortSurrounding
        }
    })
    return ports
  },

  /**
   * 获取城市航线港口列表
   * @param {String} departCity 出发城市
   * @param {String} arriveCity 到达城市
   */
  getCityLinePort(lineId) {
    return getLinePortsByIdApi({ lineId });
  },

  /**
   * 获取港口（通过港口航线ID查询）
   * @param {Number} lineId 港口航线ID
   */
  getLinePort(lineId) {
    const params = {
      LineId: lineId,
    };
    return departAndArrivePortsApi(params);
  },

  handleMarkerClick: function(e) {
    const markerId = e.detail
    const { portsList, departPort, arrivePort } = this.data
    const currentPort = portsList.find(port => port.id === markerId)
    const currentTab = currentPort.name === departPort? 'departPort': 'arrivePort'
    this.setData({
      currentPort,
      currentTab: currentTab
    })
  },
  handleLabelClick: function(e) {
    const markerId = e.detail
    const { portsList, departPort, arrivePort } = this.data
    const currentPort = portsList.find(port => port.id === markerId)
    const currentTab = currentPort.name === departPort? 'departPort': 'arrivePort'
    this.setData({
      currentPort,
      currentTab: currentTab
    })

  },
  onTap: function(e) {},
  handleTabClick: function(e) {
    const tabType = e.currentTarget.dataset.type
    const { portsList, departPort, arrivePort } = this.data
    const portName = tabType === 'departPort' ? departPort : arrivePort
    const currentPort = portsList.find(item => item.name.includes(portName))
    if(!currentPort) return
    this.setData({
      currentPort,
      currentTab: tabType
    })
  },
  portNavigate: function(e) {
    const { currentPort }= this.data
    wx.openLocation({
      latitude: parseFloat(currentPort.latitude),
      longitude: parseFloat(currentPort.longitude),
      name: currentPort.name,
      address: currentPort.address ||'',
      scale: 14
    })
    setEvent('列表', 'LB09', `^港口名称:${currentPort.name}^`)
  },
  book: function(e) {
    const { currentPort }= this.data
    wx.navigateBack()
    setEvent('列表', 'LB10', `^港口航线名称:${currentPort.name}^`)
  },
  back: function(e) {
    const { currentPort }= this.data
    wx.navigateBack()
    setEvent('列表', 'LB10', `^港口航线名称:${currentPort.name}^`)
  },
  makePhoneCall: function(e) {
    const phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone //仅为示例，并非真实的电话号码
    })
  }
});
